package com.zhy.ble.demo;

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import cn.com.heaton.bleLib.ble.L;
import cn.com.heaton.bleLib.logic.DES3Utils;

import static java.lang.Integer.parseInt;

/**
 * reference apache commons <a
 * href="http://commons.apache.org/codec/">http://commons.apache.org/codec/</a>
 *
 * @author Aub
 */
public class HexUtil {

    /**
     * 用于建立十六进制字符的输出的小写字符数组
     */
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 用于建立十六进制字符的输出的大写字符数组
     */
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data byte[]
     * @return 十六进制char[]
     */
    public static char[] encodeHex(byte[] data) {
        return encodeHex(data, true);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data        byte[]
     * @param toLowerCase <code>true</code> 传换成小写格式 ， <code>false</code> 传换成大写格式
     * @return 十六进制char[]
     */
    public static char[] encodeHex(byte[] data, boolean toLowerCase) {
        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data     byte[]
     * @param toDigits 用于控制输出的char[]
     * @return 十六进制char[]
     */
    protected static char[] encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data byte[]
     * @return 十六进制String
     */
    public static String encodeHexStr(byte[] data) {
        return encodeHexStr(data, true);
    }

    static public String Byte2Hex(Byte inByte)//1字节转2个Hex字符
    {
        return String.format("%02x", inByte).toUpperCase();
    }


    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data        byte[]
     * @param toLowerCase <code>true</code> 传换成小写格式 ， <code>false</code> 传换成大写格式
     * @return 十六进制String
     */
    public static String encodeHexStr(byte[] data, boolean toLowerCase) {
        return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data     byte[]
     * @param toDigits 用于控制输出的char[]
     * @return 十六进制String
     */
    protected static String encodeHexStr(byte[] data, char[] toDigits) {
        return new String(encodeHex(data, toDigits));
    }

    /**
     * 将十六进制字符数组转换为字节数组
     *
     * @param data 十六进制char[]
     * @return byte[]
     * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度，将抛出运行时异常
     */
    public static byte[] decodeHex(char[] data) {

        int len = data.length;

        if ((len & 0x01) != 0) {
            throw new RuntimeException("Odd number of characters.");
        }

        byte[] out = new byte[len >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f = f | toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    /**
     * 将十六进制字符转换成一个整数
     *
     * @param ch    十六进制char
     * @param index 十六进制字符在字符数组中的位置
     * @return 一个整数
     * @throws RuntimeException 当ch不是一个合法的十六进制字符时，抛出运行时异常
     */
    protected static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal character " + ch
                    + " at index " + index);
        }
        return digit;
    }

    static public byte HexToByte(String inHex) throws NumberFormatException//Hex字符串转byte
    {
        return (byte) parseInt(inHex, 16);
    }

    //转hex字符串转字节数组
    static public byte[] HexToByteArr(String inHex)//hex字符串转字节数组
    {
        int hexlen = inHex.length();
        byte[] result;
        if (isOdd(hexlen) == 1) {//奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {//偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            try {
                result[j] = HexToByte(inHex.substring(i, i + 2));
            } catch (Exception e) {
                result[j] = (byte) parseInt("00", 16);
            }
            j++;
        }
        return result;
    }

    // 判断奇数或偶数，位运算，最后一位是1则为奇数，为0是偶数
    public static int isOdd(int num) {
        return num & 0x1;
    }

    /**
     * 数组倒序
     *
     * @param myByte
     * @return
     */
    public static byte[] reverse(byte[] myByte) {
        byte[] newByte = new byte[myByte.length];

        for (int i = 0; i < myByte.length; i++) {
            newByte[i] = myByte[myByte.length - 1 - i];
        }
        return newByte;
    }

    public static void main(String[] args) {
//        String data = "dc3ebb147db1a9224edd6dad72c6c37b";
//        byte[] src = HexUtil.HexToByteArr(data);
//        byte[] result = HttpURLConnHelper.loadByteFromLocal(src);
//        System.out.print(HexUtil.encodeHexStr(result));
//        System.out.print("\neb73b9de853ae454\n");
//        String time = "201801061004";
//        String device = "35448106";
//        String communityId = "1214235636757";
//        String result = HttpURLConnHelper.generateQrCodeString(time, communityId, device);
//        System.out.print("\nresult:---->" + result);

        String pwd = "FA02610065351801FA02610065351801";

//        String pwd = "FA 02 61 00 65 35 18 01 FA 02 61 00 65 35 18 01";

        byte[] key = new byte[]{(byte) 0xfa, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01, (byte) 0xFA, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01, (byte) 0xFA, 0x02, 0x61, 0x00, 0x65, 0x35, 0x18, 0x01};
//        System.out.print("key>>>: " + cn.com.heaton.bleLib.logic.HexUtil.encodeHexStr(key) + "\n");
//        String keyStr = new String(key);
//        System.out.print("key>>>: " + keyStr + "\n");


        //元数据    8d5af4288f5efc36
        //我的值    6cb9f4ba2c0d66e2
        //他的值    B28095F77E8C9C04
        byte[] data = new byte[]{(byte) 0x8d, 0x5a, (byte) 0xf4, 0x28, (byte) 0x8f, 0x5e, (byte) 0xfc, 0x36};


        System.out.print(">>>: " + cn.com.heaton.bleLib.logic.HexUtil.encodeHexStr(data) + "\n");
        byte[] result = DES3Utils.encryptMode(key, data);
        System.out.print(">>>: " + cn.com.heaton.bleLib.logic.HexUtil.encodeHexStr(result) + "\n");


    }

}
